package com.tt.fashionWebSite.service.imp;

import com.tt.fashionWebSite.dao.*;
import com.tt.fashionWebSite.domain.*;
import com.tt.fashionWebSite.dto.*;
import com.tt.fashionWebSite.service.Ad_ProductDetailService;
import com.tt.fashionWebSite.service.Ad_ProductPictureService;
import com.tt.fashionWebSite.service.GenericService;
import com.tt.fashionWebSite.util.UploadFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.util.List;

@Service("ad_productPictureService")
public class Ad_ProductPictureServiceImp extends GenericService implements Ad_ProductPictureService {
    @Autowired
    @Qualifier("hinhAnhSanPham")
    private HinhAnhSanPhamDao hinhAnhSanPhamDao;

    @Autowired
    @Qualifier("chiTietSanPham")
    private ChiTietSanPhamDao chiTietSanPhamDao;

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int insertProductPicture(MultipartFile files, String maCTSP) {
       UploadFile uploadFile = new UploadFile();
       String fileName = uploadFile.saveImage(files);

       ChiTietSanPham chiTietSanPham = new ChiTietSanPham();
       chiTietSanPham.setMaCTSP(maCTSP);
       HinhAnhSanPham hinhAnhSanPham = new HinhAnhSanPham();
       hinhAnhSanPham.setTenHinh(fileName);
       hinhAnhSanPham.setChiTietSanPham(chiTietSanPham);

       hinhAnhSanPhamDao.insert(hinhAnhSanPham);

       return JsonResponseCode.SUCCESS;
        //save image into database
//        hinhAnhSanPham = new HinhAnhSanPham();
//        hinhAnhSanPham.setTenHinh(pictureDto.getTenHinh());
/*        File file = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg");
        byte[] bFile = new byte[(int) file.length()];

        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            //convert file into array of bytes
            fileInputStream.read(bFile);
            fileInputStream.close();
            return JsonResponseCode.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResponseCode.FAILED;
        }*/
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Integer deletePicture(String maCTSP) {
        try{
                hinhAnhSanPhamDao.deletePicture(maCTSP);
            return JsonResponseCode.SUCCESS;
        }
        catch (Exception ex) {
            return JsonResponseCode.FAILED;
        }
    }

}
